package controller

import (
	"encoding/json"
	"fmt"
	"game/drive"
	"game/util"
	"sync"
)

//入口
func Index()  {
	//添加一个端口监听
	drive.AddSocketListen(9009,"172.17.214.39")
	//监听所有端口
	test()
}


//测试端口是否启动
func test()  {
	wg := sync.WaitGroup{}
	SocketData := drive.SocketConn
	wg.Add(len(SocketData))
	for k,v := range SocketData{
		fmt.Println("开启协程监听:",k)
		//开启一个协程监听一个端口
		go SocketAccept(v,wg)
	}
	wg.Wait()
}


func SocketAccept(v drive.SocketStruct,wg sync.WaitGroup) {
	for {
		conn,errs := v.Listener.Accept()
		v.Conn = append(v.Conn,conn)
		if errs !=nil {
			util.Instance().PanicFmt("Accept 监听错误:",errs)
		}
		fmt.Println("进来人了！访问者地址及端口:",conn.RemoteAddr().String(),"连接方式为:",conn.RemoteAddr().Network())
		//维护进来这个人
		go SendSocket(&v,len(v.Conn)-1)
	}
	wg.Done()
	defer v.Listener.Close()
}

type SocketMessage struct {
	Type int `json:"type"`
	UserId int `json:"user_id"`
	UserName string `json:"user_name"`
	Data interface{} `json:"data"`
}


func SendSocket(v  *drive.SocketStruct,connKey int){
	conn := v.Conn[connKey]
	db := drive.DB
	var Messages = SocketMessage{}
	for {
		buf := make([]byte, 1024)
		n, err := conn.Read(buf)
		if err != nil {
			util.Instance().PanicFmt("客户端退出 err=:",err)
			v.Conn[connKey] = nil
			return
		}
		json.Unmarshal(buf[:n],&Messages)
		if Messages.Type == 0 && Messages.UserId == 0 {
			SendData,ok := Messages.Data.(map[string]interface{})
			if !ok {
				util.Instance().PanicFmt(" Messages.Data.(map[string]string) 结构体错误")
				continue
			}
			rows, err := db.Query("SELECT user_id,user_name FROM shop_user WHERE user_name=? and user_pass=?", SendData["user_name"],SendData["user_pass"])
			if err != nil {
				util.Instance().PanicFmt("SQL 错误:",err)
				continue
			}
			for rows.Next() {
				if err := rows.Scan(&Messages.UserId,&Messages.UserName); err != nil {
					util.Instance().PanicFmt("SQL 错误:",err)
				}
			}
			if Messages.UserId == 0 {
				util.Instance().PanicFmt("账号密码错误,等待重新验证")
				Messages.Data = map[string]interface{}{"code":0,"message":"账号密码错误,请重试"}
				resError,_:=json.Marshal(Messages)
				conn.Write(resError)
				continue
			}else{
				resError,_:=json.Marshal(Messages)
				conn.Write(resError)
				continue
			}
		}
		resMessage,_:=json.Marshal(Messages)
		for ks,vs:=range v.Conn{
			if ks != connKey && vs != nil{
				vs.Write(resMessage)
			}
		}
	}
	defer conn.Close() //关闭conn
}